package com.rzico.sbl.ui.statistic

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import com.rzico.sbl.databinding.FragmentTotalBinding
import com.rzico.sbl.other.getBeforeDate
import com.rzico.sbl.other.getBeforeEndDate
import com.rzico.sbl.other.getBeforeFirstDate
import com.rzico.sbl.other.getEndDate
import com.rzico.sbl.other.getFirstDate
import com.rzico.sbl.other.getMondayDate
import com.rzico.sbl.other.getSundayDate
import com.rzico.sbl.other.getTodayDate
import com.rzico.sbl.other.getYearEndDate
import com.rzico.sbl.other.getYearFirstDate
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.increaseFloatAnimator
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.helper.startIncreaseAnimator
import com.xinnuo.common_ui.base.NavigationFragment
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.common_ui.utils.subscribeByFinally
import org.json.JSONObject

class TotalFragment
@JvmOverloads
constructor(
    private val index: Int = 0
) : NavigationFragment() {

    private var mBinding: FragmentTotalBinding? = null
    private var mBeginDate = getTodayDate()
    private var mEndDate = getTodayDate()

    override fun getViewModel() = get<StatisticViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = FragmentTotalBinding
        .inflate(inflater, container, false)
        .also { mBinding = it }
        .root

    override fun initTitle() {
        initData()
    }

    private fun initData() {
        mBinding?.apply {
            when (index) {
                0 -> {
                    totalAmonutHint.text = "合计收款（元）"
                    totalFirstHint.text = "线上收款(元)"
                    totalSecondHint.text = "线下收款(元)"
                    totalThirdHint.text = "记账(元)"
                }

                1 -> {
                    totalAmonutHint.text = "合计订单（单）"
                    totalFirstHint.text = "已完成"
                    totalSecondHint.text = "未完成"
                    totalThirdHint.text = "退款订单"
                }
            }

            totalFirstLl.oneClick {
                when (index) {
                    0 -> startActivityEx<FundWechatActivity>()
                    1 -> startActivityEx<CompleteActivity>()
                }
            }

            totalSecondLl.oneClick {
                when (index) {
                    0 -> startActivityEx<FundManualActivity>()
                    1 -> startActivityEx<IncompleteActivity>()
                }
            }

            totalThirdLl.oneClick {
                when (index) {
                    0 -> startActivityEx<FundBillActivity>()
                    1 -> startActivityEx<RefundActivity>()
                }
            }

            totalTimeLl
                .oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            totalTime,
                            totalTimeArrow,
                            totalTimeLl,
                            getViewModel().mTimeList
                        ) { bean ->

                            (bean.id != "7")
                                .condition {
                                    getViewModel()
                                        .mTimeList
                                        .last()
                                        .name = "自定义时间"
                                }

                            when (bean.id) {
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateData()
                                }

                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateData()
                                }

                                "3" -> {
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateData()
                                }

                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateData()
                                }

                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateData()
                                }

                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateData()
                                }

                                "7" -> {
                                    requireContext()
                                        .showTimeRangeDialog(
                                            isCurrentDate = true,
                                            isAfterLimited = true,
                                            onResult = { start, end ->
                                                getViewModel()
                                                    .mTimeList
                                                    .forEach { it.isChecked = false }

                                                getViewModel()
                                                    .mTimeList
                                                    .last()
                                                    .isChecked = true

                                                mBeginDate = start
                                                mEndDate = end
                                                bean.name = "$mBeginDate  ~  $mEndDate"
                                                totalTime.text = bean.name

                                                updateData()
                                            }
                                        )
                                }
                            }
                        }
                }
        }

        getViewModel()
            .mOrderEvent
            .observe(this) { result ->
                mBinding?.let {
                    val obj = JSONObject(result)

                    it.totalAmonut
                        .startIncreaseAnimator(
                            to = obj.optNotNull("total").intValue,
                            milliseconds = 300
                        )

                    it.totalFirst
                        .startIncreaseAnimator(
                            to = obj.optNotNull("completed").intValue,
                            milliseconds = 300
                        )

                    it.totalSecond
                        .startIncreaseAnimator(
                            to = obj.optNotNull("uncompleted").intValue,
                            milliseconds = 300
                        )

                    it.totalThird
                        .startIncreaseAnimator(
                            to = obj.optNotNull("refunded").intValue,
                            milliseconds = 300
                        )
                }
            }
    }

    private fun updateData() {
        when (index) {
            0 -> getPayTotal()
            1 -> getViewModel()
                .getOrderSum(mBeginDate, mEndDate)
        }
    }

    /**
     * Fragment切换时回调，请求数据
     */
    override fun onResume() {
        super.onResume()

        updateData()
    }

    /**
     * Fragment切换时回调，停止请求
     */
    override fun onPause() {
        super.onPause()

        getViewModel().cancelRequest()
    }

    /**
     * 收款数
     */
    private fun getPayTotal() {
        getViewModel()
            .getPaySum(mBeginDate, mEndDate)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { items ->
                    mBinding?.let { binding ->
                        var totalOnlineAmout = 0.0
                        var totalOfflineAmout = 0.0
                        var totalMonthAmout = 0.0

                        items.forEach {
                            when {
                                "aliPayF2FPlugin" == it.memberName -> {
                                    val amount = it.amount.doubleValue - it.refund.doubleValue
                                    totalOnlineAmout += amount
                                }

                                "aliPayPlugin" == it.memberName -> {
                                    val amount = it.amount.doubleValue - it.refund.doubleValue
                                    totalOnlineAmout += amount
                                }

                                "微信支付" in it.typeName -> {
                                    val amount = it.amount.doubleValue - it.refund.doubleValue
                                    totalOnlineAmout += amount
                                }

                                "aliOfflinePlugin" == it.memberName -> {
                                    val amount = it.amount.doubleValue - it.refund.doubleValue
                                    totalOfflineAmout += amount
                                }

                                "cashPayPlugin" == it.memberName -> {
                                    val amount = it.amount.doubleValue - it.refund.doubleValue
                                    totalOfflineAmout += amount
                                }

                                "weixinOfflinePlugin" == it.memberName -> {
                                    val amount = it.amount.doubleValue - it.refund.doubleValue
                                    totalOfflineAmout += amount
                                }

                                "couponPayPlugin" == it.memberName -> {
                                    val amount = it.amount.doubleValue - it.refund.doubleValue
                                    totalOfflineAmout += amount
                                }

                                "bankPayPlugin" == it.memberName -> {
                                    val amount = it.amount.doubleValue - it.refund.doubleValue
                                    totalOfflineAmout += amount
                                }

                                "monthPayPlugin" == it.memberName -> {
                                    val amount = it.amount.doubleValue - it.refund.doubleValue
                                    totalMonthAmout += amount
                                }
                            }
                        }

                        binding.totalFirst
                            .increaseFloatAnimator(
                                to = totalOnlineAmout.toFloat(),
                                milliseconds = 300
                            )

                        binding.totalSecond
                            .increaseFloatAnimator(
                                to = totalOfflineAmout.toFloat(),
                                milliseconds = 300
                            )

                        binding.totalThird
                            .increaseFloatAnimator(
                                to = totalMonthAmout.toFloat(),
                                milliseconds = 300
                            )

                        binding.totalAmonut
                            .increaseFloatAnimator(
                                to = (totalOnlineAmout + totalOfflineAmout + totalMonthAmout).toFloat(),
                                milliseconds = 300
                            )
                    }
                }
            )
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding = null
    }

    companion object {
        fun newInstance(index: Int) = TotalFragment(index)
    }

}